package com.ks.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ks.api.common.Result;
import com.ks.api.entity.KsUser;
import com.ks.api.entity.KsUserCostSummary;
import com.ks.api.entity.UserBinding;
import com.ks.api.mapper.KsUserMapper;
import com.ks.api.mapper.KsUserCostSummaryMapper;
import com.ks.api.mapper.UserBindingMapper;
import com.ks.api.service.UserBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/binding")
public class BindingController {

    @Autowired
    private UserBindingService userBindingService;
    
    @Autowired
    private KsUserMapper ksUserMapper;

    @Autowired
    private KsUserCostSummaryMapper ksUserCostSummaryMapper;

    @Autowired
    private UserBindingMapper userBindingMapper;

    @GetMapping("/list")
    public Result getBindingList(HttpSession session) {
        UserBinding sessionUser = (UserBinding) session.getAttribute("user");
        try {
            List<Map<String, String>> bindingList = userBindingService.getBindingList(sessionUser);
            
            // Enhance each binding with cost statistics
            for (Map<String, String> binding : bindingList) {
                String nickId = binding.get("nickId");
                // Get the KsUser to find openId
                KsUser ksUser = ksUserMapper.selectOne(
                    new LambdaQueryWrapper<KsUser>()
                        .eq(KsUser::getNickId, nickId)
                );
                
                if (ksUser != null) {
                    String openId = ksUser.getOpenId();
                    // Get cost statistics for different time periods
                    Map<String, Object> todayStats = ksUserCostSummaryMapper.getTodayCostSummaries(nickId, null);
                    Map<String, Object> yesterdayStats = ksUserCostSummaryMapper.getYesterdayCostSummaries(nickId, null);
                    Map<String, Object> weekStats = ksUserCostSummaryMapper.getWeekCostSummaries(nickId, null);
                    Map<String, Object> monthStats = ksUserCostSummaryMapper.getMonthCostSummaries(nickId, null);
                    
                    // Add statistics to binding data
                    binding.put("todayCost", todayStats.get("total_cost").toString());
                    binding.put("yesterdayCost", yesterdayStats.get("total_cost").toString());
                    binding.put("weekCost", weekStats.get("total_cost").toString());
                    binding.put("monthCost", monthStats.get("total_cost").toString());
                }
            }
            
            return Result.success(bindingList, "获取成功");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/add")
    public Result addBinding(@RequestBody Map<String, String> params, HttpSession session) {
        UserBinding user = (UserBinding) session.getAttribute("user");
        String nickId = params.get("nickId");
        try {
            Map<String, Object> result = userBindingService.addBinding(user, nickId);
            if ((Boolean)result.get("success")) {
                return Result.success(result.get("message"));
            } else {
                return Result.error((String)result.get("message"));
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/remove")
    public Result removeBinding(@RequestBody Map<String, String> params, HttpSession session) {
        UserBinding user = (UserBinding) session.getAttribute("user");
        String nickId = params.get("nickId");
        try {
            boolean success = userBindingService.removeBinding(user, nickId);
            if (success) {
                return Result.success("解除绑定成功");
            } else {
                return Result.error("解除绑定失败，可能该用户未绑定");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        Map<String, Object> result = userBindingService.register(username, password);
        if ((Boolean)result.get("success")) {
            return Result.success(result.get("message"));
        } else {
            return Result.error((String)result.get("message"));
        }
    }

    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody Map<String, String> params, HttpSession session) {
        UserBinding user = (UserBinding) session.getAttribute("user");
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        Map<String, Object> result = userBindingService.changePassword(user.getUsername(), oldPassword, newPassword);
        if ((Boolean)result.get("success")) {
            return Result.success(result.get("message"));
        } else {
            return Result.error((String)result.get("message"));
        }
    }

    @GetMapping("/bound-users-summary")
    public Result getBoundUsersCostSummary(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            HttpSession session) {
        UserBinding sessionUser = (UserBinding) session.getAttribute("user");
        if (sessionUser == null) {
            return Result.error("未找到绑定用户");
        }

        try {
            UserBinding userBinding = userBindingMapper.selectById(sessionUser.getId());
            if (userBinding == null || userBinding.getBoundUserIds() == null || userBinding.getBoundUserIds().isEmpty()) {
                return Result.error("未找到绑定用户");
            }

            // 解析绑定的用户ID列表
            List<String> boundUserIds = new ArrayList<>(Arrays.asList(userBinding.getBoundUserIds().split(",")));
            
            // 获取这些用户的成本统计数据
            Map<String, Object> result = new HashMap<>();
            
            // 获取分页数据
            Page<KsUserCostSummary> pageParam = new Page<>(page, size);
            // 修改为只获取绑定用户的数据
            Page<KsUserCostSummary> costPage = ksUserCostSummaryMapper.findCostSummariesByOpenIds(
                pageParam, boundUserIds);
            costPage.getRecords().forEach(ksUserCostSummary -> {
                ksUserCostSummary.setSysCost(ksUserCostSummary.getUserCost());
                ksUserCostSummary.setTotalCost(ksUserCostSummary.getUserCost().multiply(BigDecimal.valueOf(2)));
            });
            
            // 获取绑定用户的统计数据
            Map<String, Object> todayStats = ksUserCostSummaryMapper.getCostSummariesByOpenIds(boundUserIds, "today");
            Map<String, Object> yesterdayStats = ksUserCostSummaryMapper.getCostSummariesByOpenIds(boundUserIds, "yesterday");
            Map<String, Object> weekStats = ksUserCostSummaryMapper.getCostSummariesByOpenIds(boundUserIds, "week");
            Map<String, Object> monthStats = ksUserCostSummaryMapper.getCostSummariesByOpenIds(boundUserIds, "month");
            
            // 封装统计数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("today", todayStats);
            stats.put("yesterday", yesterdayStats);
            stats.put("week", weekStats);
            stats.put("month", monthStats);
            
            // 封装返回结果
            result.put("total", costPage.getTotal());
            result.put("pages", costPage.getPages());
            result.put("current", costPage.getCurrent());
            result.put("size", costPage.getSize());
            result.put("records", costPage.getRecords());
            result.put("stats", stats);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取数据统计数据失败: " + e.getMessage());
        }
    }
} 